const AV = require("leanengine");
const BaseService = require("./baseService");

class Service extends BaseService {
  constructor() {
    super("City");
  }

  // 切换城市
  async switchCity(ctx) {
    const { cityId } = ctx.params;
    const query = new AV.Query("City");
    // query.equalTo("objectId", cityId);
    // const city = await query.find();
    try {
      const city = await query.get(cityId);
      ctx.session.cityId = cityId;
      return {
        code: "666",
        city,
        msg: "切换成功"
      };
    } catch (error) {
      return {
        code: "666",
        msg: "切换城市失败"
      };
    }
  }

  // 打乱数组
  shuffle(arr) {
    let i = arr.length;
    while (i) {
      let j = Math.floor(Math.random() * i--);
      [arr[j], arr[i]] = [arr[i], arr[j]];
    }
    return arr;
  }

  async getList(ctx) {
    const { pageNum = 1, pageSize = 10 } = ctx.params;

    try {
      const query = new AV.Query("City");
      query.descending("name");
      const total = await query.count();
      const result = await query.find();
      let cities = result.map(city => {
        return {
          ...city.attributes,
          cityId: city.id,
          create: city.get("createdAt")
        };
      });
      return {
        code: "666",
        msg: "success",
        pageNum,
        total,
        cities
      };
    } catch (error) {
      console.log(error);
      return {
        code: error.code,
        msg: error.message
      };
    }
  }
}

module.exports = new Service();
